import java.util.ArrayList;
import java.util.List;

public class CombinationSum {
    // leetcode 组合总和
    // https://leetcode.cn/problems/combination-sum/description/?envType=study-plan-v2&envId=top-100-liked
    private List<List<Integer>> ret;
    private List<Integer> path;
    private int sum;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        ret = new ArrayList<>();
        path = new ArrayList<>();
        dfs(candidates, target, 0);
        return ret;
    }

    private void dfs(int[] candidates, int target, int index) {
        if (sum >= target) {
            if (sum == target) {
                ret.add(new ArrayList<>(path));
            }
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            path.add(candidates[i]);
            sum += candidates[i];
            dfs(candidates,target, i);
            path.remove(path.size() - 1);
            sum -= candidates[i];
        }
    }
}
